const ws = require('nodejs-websocket')
const PROT = 3001

// let num = 0 // 起名
// let num_b = 0 // 总人数
// var serve = ws.createServer(conn => {
//     console.log('有人连接了');
//     num++
//     num_b++
//     serve.userName = `用户${num}`
//     serve.total = num_b
//     broadcast(serve.userName)
//     broadcast(`总人数${num_b}`)
//     conn.on('text', str => {
//         // conn.send(`${str}?`)
//         broadcast(str)
//     })
//     conn.on('close', (code, reason) => {
//         console.log('code', code)
//         console.log('reason', reason)
//         num_b--
//         broadcast(`总人数${num_b}`)
//     })
//     conn.on('error', obj => {
//         console.log('obj', obj)
//     })
// })
var serve = ws.createServer(conn => {
    console.log('有人连接了');
    conn.on('text', str => {
        console.log('str', str)
        broadcast(str)
    })
    conn.on('close', (code, reason) => {
        console.log('code', code)
        console.log('reason', reason)
    })
    conn.on('error', obj => {
        console.log('obj', obj)
    })

})

function broadcast(msg, server = serve) {
    server.connections.forEach(function (conn) {
        // conn.sendText(msg)
        conn.send(msg)

        // conn.send(conn.beginBinary(msg))
    })
}

serve.listen(PROT, str => {
    console.log('str', str)
})